package org.doc.noliferadio;

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.doc.noliferadio.stuff.*;

public class NoLifeRadioOverlay extends javax.swing.JFrame {

    final static double VERSION = 1.1d;
    int x, y = 0;
    int fontsize = 12;
    int textspeed = 15;
    int maxWindowWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
    boolean enableTransparency = true;
    boolean showradiourl = true;
    private TextMode MODE = TextMode.STATIC;
    boolean bold = true, italic = false;
    Color color = Color.black;
    String font = Font.DIALOG;
    Thread titleupdater;
    JPopupMenu rclickmenu;
    Point preferedmidpoint;
    private MarqueeLabel songtitle;

    public NoLifeRadioOverlay() {
        try {
            setIconImage(ImageIO.read(NoLifeRadio.class.getResource("/nlr.png")));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        initComponents();
        titleupdater = new Thread(new Runnable() {
            @Override
            public void run() {
                int i = 1;
                while (true) {
                    try {
                        if (i % 5 == 0) {
                            System.out.println("[" + i + "] Checking for new song title...");
                        }
                        i++;
                        String oldtitle = songtitle.getText();
                        String newtitle = " " + NoLifeRadio.getTitle() + " ";
                        if (!oldtitle.equals(newtitle)) {
                            System.out.println("New song title found, waiting...");
                            Thread.sleep(15000);
                            songtitle.setText(newtitle);
                            System.out.println("Updating title to " + newtitle);
                            i = 0;
                            if (MODE.equals(TextMode.DYNAMIC)) {
                                packem();
                                dynamicCheck();
                            }
                        }
                        packem();
                        System.gc();
                        Thread.sleep(5000);
                    } catch (Exception ex) {
                        Logger.getLogger(NoLifeRadioOverlay.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }, "Title Updater");
        titleupdater.start();
        preferedmidpoint = new Point(getLocation().x + (getSize().width / 2), getLocation().y);
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                saveProperties();
            }
        }));
        setVisible(false);
        PropertiesManager.init();
        setProperties();
        setFontAndStuff();
        setColors(color);
        //Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        //setLocation((dim.width / 2) - (getSize().width / 2), (dim.height / 2) - (getSize().height / 2));
        setVisible(true);
    }

    public TextMode getMODE() {
        return MODE;
    }

    public void setMODE(TextMode MODE) {
        this.MODE = MODE;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        advoptsframe = new javax.swing.JFrame();
        staticmoderadio = new javax.swing.JRadioButton();
        marqueemoderadio = new javax.swing.JRadioButton();
        dynamicOpsPane = new javax.swing.JPanel();
        maxwindowwidthbutton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        widthlabel = new javax.swing.JLabel();
        maxwidthlabel = new javax.swing.JLabel();
        dynamicmoderadio = new javax.swing.JRadioButton();
        songtitlemodegroup = new javax.swing.ButtonGroup();
        songtitle = new MarqueeLabel();
        nlrurl = new javax.swing.JLabel();

        advoptsframe.setTitle("Advanced Options");
        advoptsframe.setAlwaysOnTop(true);
        advoptsframe.setResizable(false);

        songtitlemodegroup.add(staticmoderadio);
        staticmoderadio.setSelected(true);
        staticmoderadio.setText("Static Mode");
        staticmoderadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                staticmoderadioActionPerformed(evt);
            }
        });

        songtitlemodegroup.add(marqueemoderadio);
        marqueemoderadio.setText("Marquee Mode");
        marqueemoderadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                marqueemoderadioActionPerformed(evt);
            }
        });

        maxwindowwidthbutton.setText("Set Max Window Width...");
        maxwindowwidthbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                maxwindowwidthbuttonActionPerformed(evt);
            }
        });

        jLabel1.setText("Marquee Speed:");

        jLabel2.setText("Fast");

        jLabel3.setText("Slow");

        jSlider1.setMaximum(30);
        jSlider1.setMinimum(1);
        jSlider1.setMinorTickSpacing(1);
        jSlider1.setPaintLabels(true);
        jSlider1.setPaintTicks(true);
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        widthlabel.setText("15");

        maxwidthlabel.setText("0 px");

        javax.swing.GroupLayout dynamicOpsPaneLayout = new javax.swing.GroupLayout(dynamicOpsPane);
        dynamicOpsPane.setLayout(dynamicOpsPaneLayout);
        dynamicOpsPaneLayout.setHorizontalGroup(
            dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dynamicOpsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(dynamicOpsPaneLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3))
                    .addGroup(dynamicOpsPaneLayout.createSequentialGroup()
                        .addGroup(dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(dynamicOpsPaneLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(widthlabel))
                            .addGroup(dynamicOpsPaneLayout.createSequentialGroup()
                                .addComponent(maxwindowwidthbutton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(maxwidthlabel)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        dynamicOpsPaneLayout.setVerticalGroup(
            dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dynamicOpsPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(maxwindowwidthbutton)
                    .addComponent(maxwidthlabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(widthlabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(dynamicOpsPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSlider1.setValue(15);

        songtitlemodegroup.add(dynamicmoderadio);
        dynamicmoderadio.setText("Dynamic mode");
        dynamicmoderadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dynamicmoderadioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout advoptsframeLayout = new javax.swing.GroupLayout(advoptsframe.getContentPane());
        advoptsframe.getContentPane().setLayout(advoptsframeLayout);
        advoptsframeLayout.setHorizontalGroup(
            advoptsframeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(advoptsframeLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(advoptsframeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(advoptsframeLayout.createSequentialGroup()
                        .addComponent(marqueemoderadio)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(advoptsframeLayout.createSequentialGroup()
                        .addComponent(staticmoderadio, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(dynamicmoderadio)))
                .addContainerGap())
            .addComponent(dynamicOpsPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        advoptsframeLayout.setVerticalGroup(
            advoptsframeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(advoptsframeLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(advoptsframeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(staticmoderadio)
                    .addComponent(dynamicmoderadio))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(marqueemoderadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dynamicOpsPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        for (Component c : dynamicOpsPane.getComponents()) {
            c.setEnabled(marqueemoderadio.isSelected());
        }

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setUndecorated(true);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                formMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                formMouseExited(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        songtitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        songtitle.setText(" "+NoLifeRadio.getTitle()+" ");
        getContentPane().add(songtitle, java.awt.BorderLayout.PAGE_START);

        nlrurl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        nlrurl.setText("http://nolife-radio.com");
        getContentPane().add(nlrurl, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            System.exit(0);
        }
    }//GEN-LAST:event_formKeyPressed

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
        setLocation(evt.getXOnScreen() - x, evt.getYOnScreen() - y);
    }//GEN-LAST:event_formMouseDragged

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
        x = evt.getX();
        y = evt.getY();
    }//GEN-LAST:event_formMouseMoved

    private void formMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseEntered
        if (enableTransparency) {
            setOpaque(true);
            AWTUtilitiesWrapper.setWindowOpacity(this, 0.5f);
        }
    }//GEN-LAST:event_formMouseEntered

    private void formMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseExited
        if (enableTransparency) {
            setOpaque(false);
            AWTUtilitiesWrapper.setWindowOpacity(this, 1f);
        }
    }//GEN-LAST:event_formMouseExited

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        if (evt.getButton() == 3) {
            rclickmenu = new JPopupMenu();
            JMenuItem textcolor = new JMenuItem("Color...");
            JMenuItem textsize = new JMenuItem("Font...");
            JMenuItem advopts = new JMenuItem("Advanced Options...");
            JCheckBoxMenuItem trans = new JCheckBoxMenuItem("Use Transprancy", enableTransparency);
            JCheckBoxMenuItem showurl = new JCheckBoxMenuItem("Show radio url", showradiourl);
            JMenuItem copysongname = new JMenuItem("Copy song title to clipboard");
            JMenuItem copyurl = new JMenuItem("Copy radio url to clipboard");
            JMenuItem reset = new JMenuItem("Reset");

            textcolor.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    color = JColorChooser.showDialog(rootPane, "Pick yerself a pretty color", color);
                    songtitle.setForeground(color);
                    nlrurl.setForeground(color);
                    pack();
                    formMouseExited(null);
                }
            });

            textsize.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
                    String[] fontnames = ge.getAvailableFontFamilyNames();
                    JComboBox aivfonts = new JComboBox(fontnames);
                    aivfonts.setSelectedItem(font);
                    aivfonts.setRenderer(new Rend());
                    JSpinner spin = new JSpinner(new SpinnerNumberModel(fontsize, 0, 50000, 1));
                    JCheckBox fbold = new JCheckBox("Bold", bold);
                    JCheckBox fitalics = new JCheckBox("Italics: ", italic);

                    spin.addChangeListener(new ChangeListener() {
                        @Override
                        public void stateChanged(ChangeEvent e) {
                            fontsize = Integer.parseInt(((JSpinner) e.getSource()).getValue().toString());
                            setFontAndStuff();
                        }
                    });
                    fbold.addChangeListener(new ChangeListener() {
                        @Override
                        public void stateChanged(ChangeEvent e) {
                            bold = ((JCheckBox) e.getSource()).isSelected();
                            setFontAndStuff();
                        }
                    });
                    fitalics.addChangeListener(new ChangeListener() {
                        @Override
                        public void stateChanged(ChangeEvent e) {
                            italic = ((JCheckBox) e.getSource()).isSelected();
                            setFontAndStuff();
                        }
                    });
                    aivfonts.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            font = ((JComboBox) e.getSource()).getSelectedItem().toString();
                            setFontAndStuff();
                        }
                    });

                    for (boolean r = true; r;) {
                        JOptionPane.showConfirmDialog(rootPane, new Object[]{"Text size: ", spin, fbold, fitalics, aivfonts},
                                "How do ye want yer text to look?", JOptionPane.OK_CANCEL_OPTION);
                        try {
                            Integer.parseInt(spin.getValue().toString());
                            break;
                        } catch (Exception ee) {
                        }
                    }
                    fontsize = Integer.parseInt(spin.getValue().toString());
                    bold = fbold.isSelected();
                    italic = fitalics.isSelected();
                    font = aivfonts.getSelectedItem().toString();
                    setFontAndStuff();
                }
            });

            trans.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    enableTransparency = ((JCheckBoxMenuItem) e.getSource()).isSelected();
                    setOpaque(true);
                    formMouseExited(null);
                }
            });

            showurl.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    showradiourl = ((JCheckBoxMenuItem) e.getSource()).isSelected();
                    nlrurl.setVisible(showradiourl);
                    packem();
                }
            });

            advopts.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    advoptsframe.setVisible(bold);
                    advoptsframe.setLocation(preferedmidpoint);
                    advoptsframe.setAlwaysOnTop(true);
                    advoptsframe.pack();
                }
            });

            copysongname.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(songtitle.getText().trim()), null);
                    System.out.println("Song title copied to clipboard");
                }
            });

            copyurl.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(nlrurl.getText().trim()), null);
                    System.out.println("Nolife-radio url copied to clipboard");
                }
            });

            reset.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (JOptionPane.showConfirmDialog(rootPane, "Reset all options to default?", "", JOptionPane.YES_NO_OPTION) == 0) {
                        fontsize = 12;
                        bold = true;
                        italic = false;
                        color = Color.black;
                        font = Font.DIALOG;
                        setFontAndStuff();
                        setColors(color);
                        setMODE(TextMode.STATIC);
                        switch (MODE) {
                            case STATIC:
                                staticmoderadio.setSelected(true);
                                staticmoderadioActionPerformed(null);
                                break;
                            case MARQUEE:
                                marqueemoderadio.setSelected(true);
                                marqueemoderadioActionPerformed(null);
                                break;
                            case DYNAMIC:
                                dynamicmoderadio.setSelected(true);
                                dynamicmoderadioActionPerformed(null);
                                break;
                        }
                        enableTransparency = true;
                        maxWindowWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
                        showradiourl = true;
                        textspeed = 15;
                        songtitle.setSpeed(textspeed);
                        jSlider1.setValue(15);
                        setLocation(0, 0);
                    }
                }
            });

            rclickmenu.add(textcolor);
            rclickmenu.add(textsize);
            rclickmenu.add(advopts);
            rclickmenu.add(new JPopupMenu.Separator());
            rclickmenu.add(trans);
            rclickmenu.add(showurl);
            rclickmenu.add(new JPopupMenu.Separator());
            rclickmenu.add(copysongname);
            rclickmenu.add(copyurl);
            rclickmenu.add(new JPopupMenu.Separator());
            rclickmenu.add(reset);
            rclickmenu.show(this, x, y);
        }
    }//GEN-LAST:event_formMouseClicked

    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        preferedmidpoint = new Point(evt.getComponent().getLocation().x + (evt.getComponent().getSize().width / 2), evt.getComponent().getLocation().y);
    }//GEN-LAST:event_formComponentMoved

    private void marqueemoderadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_marqueemoderadioActionPerformed
        for (Component component : dynamicOpsPane.getComponents()) {
            component.setEnabled(true);
        }
        maxwindowwidthbutton.setEnabled(false);
        maxwidthlabel.setEnabled(false);
        setMODE(TextMode.MARQUEE);
        songtitle.setMode(TextMode.MARQUEE);
        repaint();
        advoptsframe.pack();
    }//GEN-LAST:event_marqueemoderadioActionPerformed

    private void staticmoderadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_staticmoderadioActionPerformed
        for (Component component : dynamicOpsPane.getComponents()) {
            component.setEnabled(false);
        }
        maxwindowwidthbutton.setEnabled(false);
        setMODE(TextMode.STATIC);
        songtitle.setMode(TextMode.STATIC);
        advoptsframe.pack();
    }//GEN-LAST:event_staticmoderadioActionPerformed

    private void maxwindowwidthbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_maxwindowwidthbuttonActionPerformed
        final JFrame j = new JFrame();
        j.add(new GhostPanel());
        j.setDefaultCloseOperation(3);
        j.setUndecorated(true);
        j.setAlwaysOnTop(true);
        j.setResizable(false);
        j.setCursor(Cursor.CROSSHAIR_CURSOR);
        j.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                    j.setVisible(false);
                    j.dispose();
                }
            }
        });
        j.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
                GhostPanel.start = e.getLocationOnScreen();
                GhostPanel.end = e.getLocationOnScreen();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                GhostPanel.end = e.getLocationOnScreen();
                maxWindowWidth = Math.abs(GhostPanel.end.x - GhostPanel.start.x);
                maxwidthlabel.setText(maxWindowWidth + " px");
                j.setVisible(false);
                j.dispose();
                dynamicCheck();
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        j.addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent e) {
                GhostPanel.end = e.getLocationOnScreen();
            }

            @Override
            public void mouseMoved(MouseEvent e) {
            }
        });
        j.setVisible(true);
        j.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        AWTUtilitiesWrapper.setWindowOpacity(j, 0.6f);
    }//GEN-LAST:event_maxwindowwidthbuttonActionPerformed

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
        textspeed = ((JSlider) evt.getSource()).getValue();
        songtitle.setSpeed(textspeed);
        widthlabel.setText(Integer.toString(textspeed));
    }//GEN-LAST:event_jSlider1StateChanged

    private void dynamicmoderadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dynamicmoderadioActionPerformed
        for (Component component : dynamicOpsPane.getComponents()) {
            component.setEnabled(true);
        }
        maxwindowwidthbutton.setEnabled(true);
        setMODE(TextMode.DYNAMIC);
    }//GEN-LAST:event_dynamicmoderadioActionPerformed

    public void dynamicCheck() {
        packem();
        repaint();
        System.out.print("Max window width is " + maxWindowWidth + ", current is " + getWidth());
        if (getWidth() > maxWindowWidth) {
            songtitle.setMode(TextMode.MARQUEE);
            //System.out.println(", setting mode to marquee.");
        } else {
            songtitle.setMode(TextMode.STATIC);
            //System.out.println(", setting mode to static.");
        }
        packem();
        repaint();
    }

    private void setOpaque(boolean t) {
        AWTUtilitiesWrapper.setWindowOpaque(this, t);
        packem();
    }

    private void setFontAndStuff(String font, boolean bold, boolean italic, int fontsize) {
        Font newfont;
        if (bold && italic) {
            newfont = new Font(font, Font.BOLD | Font.ITALIC, fontsize);
        } else if (bold && !italic) {
            newfont = new Font(font, Font.BOLD, fontsize);
        } else if (!bold && italic) {
            newfont = new Font(font, Font.ITALIC, fontsize);
        } else {
            newfont = new Font(font, Font.PLAIN, fontsize);
        }
        songtitle.setFont(newfont);
        nlrurl.setFont(newfont);

//        System.out.println("Updated font.\n"
//                + " - Size: " + fontsize + "\n"
//                + " - Bold: " + bold + "\n"
//                + " - Italic: " + italic + "\n"
//                + " - Font: " + font);

        packem();
        formMouseExited(null);
    }

    private void setFontAndStuff() {
        setFontAndStuff(font, bold, italic, fontsize);
    }

    private void setColors(Color c) {
        songtitle.setForeground(c);
        nlrurl.setForeground(c);
    }

    private void setColors() {
        setColors(color);
    }

    public void packem() {
        pack();
        validate();
        pack();
        validate();
        songtitle.validate();
        if (isShowing()) {
            checkMidpos();
        }
    }

    public void checkMidpos() {
        Point windowpos = getLocationOnScreen();
        Point newmid = new Point(windowpos.x + (getSize().width / 2), windowpos.y);
        if (!newmid.equals(preferedmidpoint)) {
            System.err.println("Window is not centered!  Should be [" + preferedmidpoint.x + "," + preferedmidpoint.y + "], "
                    + "is [" + newmid.x + "," + newmid.y + "].  Moving!");
        }
        setLocation(preferedmidpoint.x - (getSize().width / 2), preferedmidpoint.y);
    }

    private void setProperties() {
        font = (PropertiesManager.getProperty("FONT") != null ? PropertiesManager.getProperty("FONT") : font);
        //System.out.println("Loaded FONT=" + font);

        bold = (PropertiesManager.getProperty("BOLD") != null ? PropertiesManager.getProperty("BOLD").equalsIgnoreCase("true") : true);
        //System.out.println("Loaded BOLD=" + bold);

        italic = (PropertiesManager.getProperty("ITALIC") != null ? PropertiesManager.getProperty("ITALIC").equalsIgnoreCase("true") : false);
        //System.out.println("Loaded ITALIC=" + italic);

        try {
            fontsize = (PropertiesManager.getProperty("SIZE") != null ? Integer.parseInt(PropertiesManager.getProperty("SIZE")) : 12);
            //System.out.println("Loaded SIZE=" + fontsize);
        } catch (NumberFormatException numberFormatException) {
            fontsize = 12;
            //System.out.println("Loaded SIZE=" + fontsize);
        }

        try {
            color = new Color((PropertiesManager.getProperty("COLOR") != null ? Integer.parseInt(PropertiesManager.getProperty("COLOR")) : -16777216));
            //System.out.println("Loaded COLOR=" + color);
        } catch (NumberFormatException numberFormatException) {
            fontsize = 12;
            //System.out.println("Loaded COLOR=" + color);
        }

        enableTransparency = (PropertiesManager.getProperty("USE_TRANSPARENCY") != null
                ? PropertiesManager.getProperty("USE_TRANSPARENCY").equalsIgnoreCase("true") : false);
        //System.out.println("Loaded USE_TRANSPARENCY=" + enableTransparency);

        try {
            maxWindowWidth = (PropertiesManager.getProperty("MAX_WINDOW_WIDTH") != null
                    ? Integer.parseInt(PropertiesManager.getProperty("MAX_WINDOW_WIDTH")) : Toolkit.getDefaultToolkit().getScreenSize().width);
            //System.out.println("Loaded MAX_WINDOW_WIDTH=" + maxWindowWidth);
        } catch (NumberFormatException numberFormatException) {
            maxWindowWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
            //System.out.println("Loaded MAX_WINDOW_WIDTH=" + maxWindowWidth);
        }
        maxwidthlabel.setText(maxWindowWidth + "px");
        int nx, ny;
        try {
            nx = (PropertiesManager.getProperty("LOCATION_MID_X") != null
                    ? Integer.parseInt(PropertiesManager.getProperty("LOCATION_MID_X"))
                    : (Toolkit.getDefaultToolkit().getScreenSize().width / 2) - (getSize().width / 2));
        } catch (NumberFormatException numberFormatException) {
            nx = (Toolkit.getDefaultToolkit().getScreenSize().width / 2) - (getSize().width / 2);
        }
        try {
            ny = (PropertiesManager.getProperty("LOCATION_Y") != null
                    ? Integer.parseInt(PropertiesManager.getProperty("LOCATION_Y"))
                    : (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - (getSize().height / 2));
        } catch (NumberFormatException numberFormatException) {
            ny = (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - (getSize().height / 2);
        }
        final int fx = nx, fy = ny;
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                setLocation(fx - (getWidth() / 2), fy);
                setVisible(true);
            }
        });
        try {
            setMODE(PropertiesManager.getProperty("MODE") != null ? TextMode.valueOf(PropertiesManager.getProperty("MODE")) : null);
            songtitle.setMode(MODE);
        } catch (Exception e) {
            e.printStackTrace();
            setMODE(TextMode.STATIC);
            songtitle.setMode(MODE);
        }
        try {
            textspeed = (PropertiesManager.getProperty("TEXT_SPEED") != null ? Integer.parseInt(PropertiesManager.getProperty("TEXT_SPEED")) : 15);
            //System.out.println("Loaded TEXT_SPEED=" + textspeed);
        } catch (NumberFormatException numberFormatException) {
            textspeed = 15;
            //System.out.println("Loaded TEXT_SPEED=" + textspeed);
        } finally {
            jSlider1.setValue(textspeed);
        }
        switch (MODE) {
            case STATIC:
                staticmoderadio.setSelected(true);
                staticmoderadioActionPerformed(null);
                break;
            case MARQUEE:
                marqueemoderadio.setSelected(true);
                marqueemoderadioActionPerformed(null);
                break;
            case DYNAMIC:
                dynamicmoderadio.setSelected(true);
                dynamicmoderadioActionPerformed(null);
                break;
        }
        System.gc();
    }

    private void saveProperties() {
        PropertiesManager.saveProperty("FONT", font);
        //System.out.println("Saving FONT=" + font);

        PropertiesManager.saveProperty("BOLD", Boolean.toString(bold));
        //System.out.println("Saving BOLD=" + bold);

        PropertiesManager.saveProperty("ITALIC", Boolean.toString(italic));
        //System.out.println("Saving ITALIC=" + italic);

        PropertiesManager.saveProperty("SIZE", Integer.toString(fontsize));
        //System.out.println("Saving SIZE=" + fontsize);

        PropertiesManager.saveProperty("COLOR", Integer.toString(color.getRGB()));
        //System.out.println("Saving COLOR=" + color);

        PropertiesManager.saveProperty("USE_TRANSPARENCY", Boolean.toString(enableTransparency));
        //System.out.println("Saving USE_TRANSPARENCY=" + enableTransparency);

        PropertiesManager.saveProperty("MAX_WINDOW_WIDTH", Integer.toString(maxWindowWidth));
        //System.out.println("Saving MAX_WINDOW_WIDTH=" + maxWindowWidth);

        PropertiesManager.saveProperty("LOCATION_MID_X", Integer.toString(getLocation().x + (getWidth() / 2)));
        //System.out.println("Saving LOCATION_MID_X=" + (getLocation().x + (getWidth() / 2)));

        PropertiesManager.saveProperty("LOCATION_Y", Integer.toString(getLocation().y));
        //System.out.println("Saving LOCATION_Y=" + (getLocation().y));

        PropertiesManager.saveProperty("MODE", MODE.toString());
        //System.out.println("Saving MODE=" + MODE.toString());

        PropertiesManager.saveProperty("TEXT_SPEED", Integer.toString(textspeed));
        //System.out.println("Saving TEXT_SPEED=" + Integer.toString(textspeed));

        PropertiesManager.save();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                checkForUpdate();
                System.out.println(NoLifeRadio.getTitle());
                new NoLifeRadioOverlay().setVisible(true);
            }
        });
    }

    private static void checkForUpdate() {
        URL testurl;
        File jar = new File(NoLifeRadio.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        try {
            if (jar.isFile()) {
                double inc = 0.1;
                testurl = new URL("http://nolife-radio-overlay.googlecode.com/files/NoLifeRadioOverlayV" + (VERSION + inc) + ".jar");

                while (checkURLexist(new URL("http://nolife-radio-overlay.googlecode.com/files/NoLifeRadioOverlayV" + (VERSION + inc) + ".jar"))) {
                    testurl = new URL("http://nolife-radio-overlay.googlecode.com/files/NoLifeRadioOverlayV" + (VERSION + inc) + ".jar");
                    inc += 0.1;
                }
                if (inc == 0.1d) {
                    System.out.println("No updates available.");
                } else {
                    String newversionname = testurl.getPath().substring(testurl.getPath().lastIndexOf("/") + 1);
                    int updateyesno = JOptionPane.showConfirmDialog(null, "New version available! Download " + newversionname + "?",
                            "Update!", JOptionPane.YES_NO_OPTION);
                    if (updateyesno == 0) {
                        System.out.println("We're gonna update!");
                        update(testurl);
                    } else {
                        System.out.println("Decided not to update.");
                    }
                }
            } else {
                System.err.println("Not being run as jar, not going to check for updates.");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void update(URL newversion) {
        try {
            InputStream stream = newversion.openStream();
            File outputfile = new File(newversion.getPath().substring(newversion.getPath().lastIndexOf("/") + 1));
            ReadableByteChannel rbc = Channels.newChannel(stream);
            FileOutputStream fos = new FileOutputStream(outputfile);
            fos.getChannel().transferFrom(rbc, 0, 1 << 24);

            String n = new File(NoLifeRadio.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
            Runtime.getRuntime().exec("cmd /c \"cmd ping 127.0.0.1 && del " + n + " && java -jar " + outputfile.getName() + "\"");
            JOptionPane.showMessageDialog(null, "Updated!");
            System.exit(0);
        } catch (Exception ex) {
            Logger.getLogger(NoLifeRadioOverlay.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static boolean checkURLexist(URL url) {
        try {
            InputStream s = url.openStream();
            s.close();
        } catch (IOException ex) {
            if (ex instanceof FileNotFoundException) {
                return false;
            }
            System.err.println("Check url returned abnormal result:");
            ex.printStackTrace();
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFrame advoptsframe;
    private javax.swing.JPanel dynamicOpsPane;
    private javax.swing.JRadioButton dynamicmoderadio;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JRadioButton marqueemoderadio;
    private javax.swing.JLabel maxwidthlabel;
    private javax.swing.JButton maxwindowwidthbutton;
    private javax.swing.JLabel nlrurl;
    /*
    private javax.swing.JLabel songtitle;
    */
    private javax.swing.ButtonGroup songtitlemodegroup;
    private javax.swing.JRadioButton staticmoderadio;
    private javax.swing.JLabel widthlabel;
    // End of variables declaration//GEN-END:variables
}
